﻿using CloudStorageLight.SampleWeb.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace CloudStorageLight.SampleWeb
{
    public class MvcApplication : System.Web.HttpApplication
    {
        public MvcApplication()
        {
            var wrapper = new EventHandlerTaskAsyncHelper(DoAsyncWork);
            this.AddOnAuthenticateRequestAsync(wrapper.BeginEventHandler, wrapper.EndEventHandler);
        }
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            GlobalConfiguration.Configuration.EnsureInitialized(); 
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            using(var svc = new BlobService())
            {
                svc.EntryLog(HttpContext.Current.User.Identity.Name, "Error", this.Request.Url.PathAndQuery, HttpContext.Current.Server.GetLastError().ToString());
            }
        }

        protected void Application_BeginRequest()
        {
            Debug.WriteLine(this.Request.HttpMethod);
            Debug.WriteLine(this.Request.Url.ToString());
            foreach (var key in this.Request.Headers.AllKeys)
            {
                Debug.WriteLine(key + ":" + this.Request.Headers[key]);
            }
        }

        public void Application_OnEndRequest(Object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;

            // 認証が成功していない場合は「WWW-Authenticate」ヘッダを付加する
            if (app.Response.StatusCode == 401)
            {
                BasicAuthenticateUtil.AddUnauthorizedHeader(app);
            }
        }

        private async Task DoAsyncWork(object sender, EventArgs e)
        {
            var app = (HttpApplication)sender;
            var ctx = app.Context;
            await BasicAuthenticateUtil.Authenticate(app);

        }

    }
}
